﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twodi.Interfaces;
using Microsoft.Xna.Framework;
using Twodi.Aspect.Interfaces;

namespace Twodi.Aspect.Implemented
{
    /// <summary>
    /// Aspecto capaz de definir transformação do componente dinamicamente.
    /// Verifica propriedades do componente, Rotação, Escala e Posição e gera uma matrix de transformação.
    /// </summary>
    public class DynamicTransformationAspect : DependentAbstractAspect<IGameComponent>, ITransformation
    {
        IRotation RotationProperties;
        IScale ScaleProperties;
        IPosition PositionProperties;

        public DynamicTransformationAspect(IGameComponent component)
            : base(component)
        {
            if (component is IRotationAspect) this.RotationProperties = (component as IRotationAspect).RotationProperties;
            if (component is IScaleAspect) this.ScaleProperties = (component as IScaleAspect).ScaleProperties;
            if (component is IPositionAspect) this.PositionProperties = (component as IPositionAspect).PositionProperties;
        }

        public Matrix Transformation
        {
            get
            {
                Matrix result = Matrix.Identity;

                if (RotationProperties != null)
                {
                    result = Matrix.CreateTranslation(-RotationProperties.Origin.X, -RotationProperties.Origin.Y, 0) *
                            Matrix.CreateRotationZ(RotationProperties.Angle);
                }

                if (ScaleProperties != null)
                {
                    result = result * Matrix.CreateScale(ScaleProperties.Scale);
                }

                if (PositionProperties != null)
                {
                    result = result * Matrix.CreateTranslation(PositionProperties.Position.X, PositionProperties.Position.Y, 0);
                }

                return result;
            }
        }

        public event EventHandler<EventArgs> TransformationChanged;
    }
}
